<?php
/**
 * Created by PhpStorm.
 * User: varch
 * Date: 2019/12/25
 * Time: 0:22
 */


use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SmsPackagesStatisticsRequest;

class ObserverTxCloudSms extends ObserverTxCloud
{
    private function getSmsPackage():int
    {
        try {
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SmsClient($this->cred, "", $clientProfile);

            $req = new SmsPackagesStatisticsRequest();

            $params = '{"SmsSdkAppid":"'.__TXCLOUD_SMS_SDK_APPID__.'","Limit":20,"Offset":0}';
            $req->fromJsonString($params);


            $resp = $client->SmsPackagesStatistics($req);
            $resp = json_decode($resp->toJsonString());

            $totalSmsAvailable = 0;
            foreach ($resp->{"SmsPackagesStatisticsSet"} as $smsPackage) {
                $totalSmsAvailable += $smsPackage->{"AmountOfPackage"} - $smsPackage->{"CurrentUsage"};
            }

            return $totalSmsAvailable;
        } catch (TencentCloudSDKException $e) {
            Yii::error("Get TxCloud Balance Failed. Reason = ".$e);
            return $e->getMessage();
        }

    }

    public function observe(string $function = "PING") : void
    {
        switch ($function) {
            case "PING":
                echo "PONG";
                break;
            case "SMSPACKAGE":
                $balanceString = $this->getSmsPackage();
                echo $balanceString;
                break;
        }
    }
}